const auth = require("../../utils/auth.js");
const response = require("../../utils/response.js");
const validate = require("../../utils/validate.js");
const adminService = require("../services/adminService.js");
const bcrypt = require('bcryptjs');
const { URLSearchParams } = require('url');
const { createAdminRules, deleteAdminRules, loginAdminRules, updateAdminRules, updateMyProfileRules, updateMyPasswordRules, adminUpdateMyInfoRules } = require("../validations/adminValidation.js");

class AdminController {
    async registerAdmin(ctx){
        try {
            const adminData = await validate(ctx, createAdminRules);

            const existingUsername = await adminService.getAdminByUsername(adminData.username);
            if(existingUsername){
                return response.error(ctx, '该用户名已存在');
            }

            adminData.password = await bcrypt.hash(adminData.password, 10);
            const  { id } = await adminService.addAdmin(adminData);
            response.success(ctx, id, '注册成功');
        }catch(err) {
            console.log(err)
            response.error(ctx, err);
        }
    }
    async addAdmin(ctx) {
        try {
            const adminData = await validate(ctx, createAdminRules);

            const existingUsername = await adminService.getAdminByUsername(adminData.username);
            if(existingUsername){
                return response.error(ctx, '该用户名已存在');
            }

            if(adminData.email){
                const existingEmail = await adminService.getAdminByEmail(adminData.email);
                if(existingEmail){
                    return response.error(ctx, '该邮箱已存在');
                }
            }

            adminData.password = await bcrypt.hash(adminData.password, 10);
            const  { id } = await adminService.addAdmin(adminData);
            response.success(ctx, id, '添加成功');
        }catch(err) {
            console.log(err);
            response.error(ctx, err);
        }
    }
    async deleteAdmin(ctx){
        try{
            const adminData = await validate(ctx, deleteAdminRules);

            const affectedRows = await adminService.deleteAdmin(adminData.id);
            if(affectedRows > 0){
                response.success(ctx, adminData.id, '删除成功')
            }else{
                response.error(ctx, '删除失败')
            }
        }catch(err){
            console.log(err)
            response.error(ctx, err);
        }
    }
    async updateAdmin(ctx){
        try{
            const adminData = await validate(ctx, updateAdminRules);

            if(adminData.newPassword){
                adminData.password = await bcrypt.hash(adminData.newPassword, 10);
                // return response.error(ctx, '该接口不支持修改密码')
            }
            const affectedRows = await adminService.updateAdmin(adminData);
            if(affectedRows > 0){
                response.success(ctx, '修改成功')
            }else{
                response.error(ctx, '修改失败')
            }
        }catch(err){
            console.log(err)
            response.error(ctx, err);
        }
    }
    async adminUpdateMyInfo(ctx){
        try{
            const adminData = await validate(ctx, adminUpdateMyInfoRules);

            let id = ctx.state.admin.dataValues.id;
            const adminInstance = await adminService.getAdminById(id);
            if(!adminInstance) throw '没找到管理员';

            const passwordMatch = await bcrypt.compare(adminData.verifyPassword, adminInstance.password);
            if(!passwordMatch)throw '校验密码错误';

            const existingUsername = await adminService.getAdminByUsername(adminData.username);
            if(existingUsername && existingUsername.dataValues.id !== id)throw '该用户名已存在';

            if(adminData.newPassword){
                adminData.password = await bcrypt.hash(adminData.newPassword, 10);
            }else{
                delete adminData.password;
            }
            adminData.id = id;
            const affectedRows = await adminService.updateAdmin(adminData);
            if(affectedRows > 0){
                response.success(ctx, '修改成功')
            }else{
                response.error(ctx, '修改失败')
            }
        }catch(err){
            console.log(err)
            response.error(ctx, err);
        }
    }
    async loginAdmin(ctx){
        try {
            const adminData = await validate(ctx, loginAdminRules);

            const row = await adminService.getAdminByUsername(adminData.username);

            if(!row){
                return response.error(ctx, '用户名或密码错误');
            }
            const passwordMatch = await bcrypt.compare(adminData.password, row.password);
            if(!passwordMatch){
                return response.error(ctx, '用户名或密码错误');
            }
            response.success(ctx, auth.sing({
                data: {
                    ...row,
                    roles: ['admin', 'editor'] // 先写死给前端
                },
                role: 'admin'
            }));

        }catch(err){
            console.log(err)
            response.error(ctx, err);
        }
    }
    async adminInfo(ctx){
        if(ctx.state.admin){
            return response.success(ctx, ctx.state.admin)
        }else{
            return response.error(ctx, "登录状态已过期", null, 401)
        }
    }
    async getAdminListByPage(ctx){
        const usp = new URLSearchParams(ctx.querystring);
        let page = Number(usp.get('page')) || 1;
        let limit = Number(usp.get('limit')) || 10;
        let keyword = usp.get('keyword') || '';
        try{
            const { rows, count } = await adminService.getAdminListByPage(page, limit, keyword);
            response.success(ctx, {
                page,
                limit,
                rows,
                total: count
            });
        }catch(err){
            response.error(ctx, err);
        }
    }
    async adminLogout(ctx){
        return response.success(ctx, null);
    }
    async updateMyProfile(ctx){
        try{
            if(!ctx.state.admin){
                return response.error(ctx, "登录状态已过期", null, 401)
            }

            const adminData = await validate(ctx, updateMyProfileRules);

            const affectedRows = await adminService.updateAdmin({
                id: ctx.state.admin.id,
                username: adminData.username
            });
            if(affectedRows && affectedRows[0] > 0){
                response.success(ctx, null, '修改成功');
            }else{
                response.error(ctx, '修改失败');
            }
        }catch(err){
            console.log(err)
            response.error(ctx, err);
        }
    }
    async updateMyPassword(ctx){
        try{
            if(!ctx.state.admin){
                return response.error(ctx, "登录状态已过期", null, 401)
            }

            const adminData = await validate(ctx, updateMyPasswordRules);
            console.log(adminData.newPassword, ctx.state.admin.password)
            const passwordMatch = await bcrypt.compare(adminData.newPassword, ctx.state.admin.password);
            if(!passwordMatch){
                return response.error(ctx, '旧密码错误');
            }

            const affectedRows = await adminService.updateAdmin({
                id: ctx.state.admin.id,
                password: await bcrypt.hash(adminData.newPassword, 10)
            });
            if(affectedRows > 0){
                response.success(ctx, null, '修改成功');
            }else{
                response.error(ctx, '修改失败');
            }
        }catch(err){
            console.log(err)
            response.error(ctx, err);
        }
    }
}


module.exports = new AdminController();